package com.tunnel.service.server;



import com.tunnel.common.config.server.ServiceConfig;
import com.tunnel.common.protocol.DecodeHandler;
import com.tunnel.common.protocol.EncoderHandler;

import com.tunnel.service.hendler.TunnelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
 * 和客户端的通道
 */
public class TunnleServer implements Server {


    @Override
    public void init() {

    }

    @Override
    public void shutdown() {

    }

    @Override
    public void start(ServiceConfig serviceConfig) throws InterruptedException {
        // 创建事件循环组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        // 基础netty一套流程
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_RCVBUF, 16 * 1024);

        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //得到pipeline
                ChannelPipeline pipeline = ch.pipeline();
                // 加入自定义解码和编码
                pipeline.addLast(new DecodeHandler());
                pipeline.addLast(new EncoderHandler());
                // 自定义数据格式
                pipeline.addLast(new TunnelHandler());
            }
        });
        // 绑定端口数据
        ChannelFuture channelFuture = serverBootstrap.bind(serviceConfig.getListenPort()).sync();
        //监听关闭
        channelFuture.channel().closeFuture().sync();
    }
}
